package org.ww.seckill.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @program: gmall
 * @description:
 * @author: ww
 * @create: 2024-10-28 10:35
 **/

@Configuration
public class RabbitmqConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * @param correlationData 关联当前消息的唯一id，可以在发送消息的时候指定，以确定是那条消息发送成功或者失败
             * @param ack 是否发送成功
             * @param cause 发送失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("-----------------confirmCallback-----------------");
                System.out.println("correlationData==>"+correlationData);
                System.out.println("ack==>"+ack+"-----cause==>"+cause);
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * @param message 消息内容
             * @param replyCode 回应的状态码
             * @param replyText 回应的内容
             * @param exchange  当前消息由哪个交换机发送过来
             * @param bindingKey 发送消息时绑定的路由键
             *
             * 测试的时候可以指定不正确的路由键进行模拟
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String bindingKey) {
                System.out.println("-----------------returnCallback-----------------");
                System.out.println("message===>"+message);
                System.out.println("replycode===>"+replyCode + "---replyText==>"+replyText+"---exchange==>"+exchange+"---bindingKey==>"+bindingKey);
                System.out.println("correlationId==>"+message.getMessageProperties().getCorrelationId());
            }
        });
    }


    /**
     * 此处如果放在外部类的话会出现循环依赖问题
     */
    static class MessaeConverterConfig{
        @Bean
        public MessageConverter messageConverter(){
            return new Jackson2JsonMessageConverter();
        }
    }
}
